package com.xhy.documents_collection.thread_pool;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.entity.PO.log.LoginLog;
import com.xhy.documents_collection.entity.PO.log.FileLog;
import com.xhy.documents_collection.entity.PO.log.SysLog;
import com.xhy.documents_collection.service.FileLogService;
import com.xhy.documents_collection.service.LoginLogService;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.service.sys.SysLogService;
import com.xhy.documents_collection.utils.SpringUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.List;

/**
 * Author: Xhy
 * CreateTime: 2022-11-17 15:54
 * 日志线程,用于处理AOP中保存日志异步化
 */
public class LogThreadPool {

    private static ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

    private static int cpu = Runtime.getRuntime().availableProcessors();

    static {
        // 配置核心线程数
        executor.setCorePoolSize(cpu);
        // 配置最大线程数
        executor.setMaxPoolSize(cpu);
        // 配置队列大小
        executor.setQueueCapacity(100);
        // 配置线程池中的线程的名词前缀
        executor.setThreadNamePrefix("log-");
        // 拒绝策略
        executor.initialize();
    }

    /**
     * 保存文件日志
     * @param fileLog
     */
    public static void addFileLog(FileLog fileLog){
        executor.execute(()->SpringUtil.getBean(FileLogService.class).save(fileLog));

    }

    /**
     * 保存操作日志
     * @param sysLog
     */
    public static void addOperLog(SysLog sysLog){
        executor.execute(()->SpringUtil.getBean(SysLogService.class).save(sysLog));
    }

    /**
     * 保存登录日志
     * @param loginLog
     */
    public static void addLoginLog(LoginLog loginLog){
        executor.execute(()->SpringUtil.getBean(LoginLogService.class).save(loginLog));
    }

    /**
     * 发布公告后的操作
     * 鬼名字不知道起什么好
     * 并且如果再来个线程池我也懒
     */
    public static void helpMe(){
        executor.execute(()->{
            UserService userService = SpringUtil.getBean(UserService.class);
            List<User> list = userService.list(new LambdaQueryWrapper<User>().select(User::getId));
            list.forEach(user -> {
                user.setNoticeState(false);
            });

            userService.updateBatchById(list);
        });
    }
}
